package cn.itcast.service.impl;

import cn.itcast.mapper.EmpExprMapper;
import cn.itcast.mapper.EmpMapper;
import cn.itcast.pojo.*;
import cn.itcast.service.EmpLogService;
import cn.itcast.service.EmpService;
import cn.itcast.utils.JwtUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;


    /*添加事务，默认为发生运行时异常回归，用rollbackFor指定回滚的异常*/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Emp emp) {
        try {
            //添加基础字段
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            //插入数据
            empMapper.save(emp);
            List<EmpExpr> exprList = emp.getExprList();

            //要判断非空
            if (!CollectionUtils.isEmpty(exprList)) {
                //将emp的id赋值费jogExpr 的empId
                emp.getExprList().forEach(s ->
                        s.setEmpId(emp.getId())
                );
                //利用mapper.xml批量插入
                empExprMapper.saveBatch(emp.getExprList());
            }
        } finally {
            //操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "添加员工" + emp.toString());
            empLogService.insertLog(empLog);
        }

    }

    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
//        //起始索引
//        int start = (page -1)*pageSize;
//        List<Emp> empList= empMapper.page(start,pageSize);
//        PageResult<Emp> pageResult = new PageResult<>();
//
//        /*获取条数*/
//        long count = empMapper.count();
//        pageResult.setRows(empList);
//        pageResult.setTotal(count);
//        return pageResult;

        /*1.设置起始索引和每页查询的条数*/
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        List<Emp> list = empMapper.page(empQueryParam);
        Page<Emp> empPage = (Page<Emp>) list;
        //2.转成Page<Emp>才能获取自己有的东西 （page<E> 是 ArrayList<E>的子类；
        PageResult<Emp> pageResult = new PageResult<Emp>(empPage.getResult(), empPage.getTotal());
//        PageResult<Emp> build = PageResult.<Emp>builder().rows(empPage.getResult()).total(empPage.getTotal()).build();
        return pageResult;

    }

    @Override
    public List<Emp> list() {

        return empMapper.list();
    }

    /*批量删除*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatchById(List<Integer> ids) {

        try {
            //1.先删除emp
            empMapper.deleteBatchById(ids);

            //2.后删除emp_expr
            empExprMapper.deleteBatchByEmpId(ids);
        } finally {
            EmpLog empLog = EmpLog.builder().operateTime(LocalDateTime.now()).info("删除员工id=" + ids).build();
            empLogService.insertLog(empLog);
        }


    }

    @Override
    public Emp getEmpById(Integer id) {

        return empMapper.getEmpById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(Emp emp) {
        //1.修改emp
        //填充基础信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateEmp(emp);

        //2.删除Exp_Expr
        empExprMapper.deleteBatchByEmpId(List.of(emp.getId()));

        //3.添加Exp_Expr
        List<EmpExpr> exprList = emp.getExprList();

        //
        if (!CollectionUtils.isEmpty(exprList)) {
            //因为新增的数据是无empId的，所有需要额外绑定
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.saveBatch(exprList);
        }

    }

    @Override
    public LoginInfo login(Emp emp) {
        //根据用户名查询对应的员工对象，再匹配密码
        Emp empLogin = empMapper.getEmpByUsername(emp.getUsername());
        //判断是否为空
        if (empLogin == null) {
            throw new RuntimeException("用户名为空");
        }
        //校验密码
        if (!empLogin.getPassword().equals(emp.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        //生成token令牌
        Map<String,Object> claims = new HashMap();
        claims.put("id",empLogin.getId());
        claims.put("username",empLogin.getUsername());
        claims.put("name",empLogin.getName());
        String token = JwtUtils.generateJwt(claims);
        //
        LoginInfo build = LoginInfo.builder().id(empLogin.getId())
                .username(empLogin.getUsername()).
                name(empLogin.getName()).token(token).build();
        return build;
    }
}
